namespace CIS
{
    using CISLib;
    using CISLib.Mail;
    using ComponentArt.Web.UI;
    using FreeTextBoxControls;
    using System;
    using System.Collections;
    using System.Drawing;
    using System.Text.RegularExpressions;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;

    public class SendMailWeb : Page
    {
        protected DropDownList AreaDdl;
        protected Button btnSend;
        protected FreeTextBox ftbBody;
        protected Label lbArea;
        protected HtmlTableRow MessageRow;
        protected UserPrincipal Principal = null;
        protected RequiredFieldValidator RequiredFieldValidator1;
        protected RequiredFieldValidator RequiredFieldValidator2;
        protected ComponentArt.Web.UI.TreeView tvRoles;
        protected TextBox txtFrom;
        protected TextBox txtInputEmail;
        protected TextBox txtSubject;

        private void AreaDdl_SelectedIndexChanged(object sender, EventArgs e)
        {
            Role[] roles = ManageRole.GetRoleAry(new Guid(this.AreaDdl.SelectedValue));
            this.tvRoles.Nodes.Clear();
            if (roles != null)
            {
                foreach (Role role in roles)
                {
                    TreeViewNode roleNode = new TreeViewNode();
                    roleNode.Text = role.RoleName;
                    roleNode.ID = role.RoleId.ToString();
                    roleNode.ToolTip = role.RoleDescr;
                    roleNode.ShowCheckBox = true;
                    this.tvRoles.Nodes.Add(roleNode);
                }
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (this.tvRoles.CheckedNodes.Length == 0)
            {
                this.ShowMessage(Color.Red, "None a mail recipient(to) selected.");
            }
            else
            {
                string from = this.txtFrom.Text;
                string subject = this.txtSubject.Text;
                string contentHtml = this.ftbBody.Text;
                string[] emails = this.GetMailRecipients();
                for (int i = 0; i < emails.Length; i++)
                {
                    ManageMail.InsertNewMail(from, emails[i], subject, DateTime.Now, 2, contentHtml);
                }
                string recipients = string.Join(",", emails);
                this.ShowMessage(Color.Red, "Send mails succeed");
                this.txtSubject.Text = "";
                this.ftbBody.Text = "";
                new SendMailEx().SendMail();
            }
        }

        private string[] GetMailRecipients()
        {
            Hashtable table = new Hashtable();
            foreach (TreeViewNode node in this.tvRoles.CheckedNodes)
            {
                string mail = node.Value;
                if (this.IsValidEmail(mail) && !table.ContainsKey(mail))
                {
                    table.Add(mail, "");
                }
            }
            string[] mailAddressAry = this.txtInputEmail.Text.Trim().Split(new char[] { ';' });
            for (int i = 0; i < mailAddressAry.Length; i++)
            {
                if (this.IsValidEmail(mailAddressAry[i]) && !table.ContainsKey(mailAddressAry[i]))
                {
                    table.Add(mailAddressAry[i], "");
                }
            }
            string[] recipients = new string[table.Keys.Count];
            table.Keys.CopyTo(recipients, 0);
            table.Clear();
            return recipients;
        }

        private void InitializeComponent()
        {
            this.AreaDdl.SelectedIndexChanged += new EventHandler(this.AreaDdl_SelectedIndexChanged);
            this.tvRoles.NodeCheckChanged += new ComponentArt.Web.UI.TreeView.NodeCheckChangedEventHandler(this.tvRoles_NodeCheckChanged);
            this.btnSend.Click += new EventHandler(this.btnSend_Click);
            base.Load += new EventHandler(this.Page_Load);
        }

        private void InitPage()
        {
            Area[] area = ManageArea.GetAreaAryViaId(this.Principal.SysUser.UserId);
            this.AreaDdl.Items.Clear();
            for (int i = 0; i < area.Length; i++)
            {
                ListItem tmpListItem = new ListItem();
                tmpListItem.Text = area[i].AreaName;
                tmpListItem.Value = area[i].AreaId.ToString();
                this.AreaDdl.Items.Add(tmpListItem);
            }
            this.txtFrom.Text = MailConfig.SmtpSender;
            Role[] roles = ManageRole.GetRoleAry(new Guid(this.AreaDdl.SelectedValue));
            if (roles != null)
            {
                foreach (Role role in roles)
                {
                    TreeViewNode roleNode = new TreeViewNode();
                    roleNode.Text = role.RoleName;
                    roleNode.ID = role.RoleId.ToString();
                    roleNode.ToolTip = role.RoleDescr;
                    roleNode.Value = "ROLE" + role.RoleName;
                    ArrayList list = new ArrayList();
                    SysUser[] userAry = ManageUser.GetUserAryViaRoleId(role.RoleId);
                    if (userAry != null)
                    {
                        foreach (SysUser user in userAry)
                        {
                            TreeViewNode userNode = new TreeViewNode();
                            userNode.ShowCheckBox = true;
                            userNode.ID = string.Format("USER_{0}_{1}", role.RoleId.ToString("N"), user.UserId.ToString("N"));
                            userNode.Text = string.Format("{0}&lt;{1}&gt;", user.LoginName, user.UserEmail);
                            userNode.Value = string.Format("{0}", user.UserEmail);
                            roleNode.Nodes.Add(userNode);
                        }
                    }
                    roleNode.ShowCheckBox = true;
                    this.tvRoles.Nodes.Add(roleNode);
                }
            }
        }

        private bool IsValidEmail(string email)
        {
            Regex reg = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            return reg.IsMatch(email);
        }

        protected override void OnInit(EventArgs e)
        {
            this.InitializeComponent();
            base.OnInit(e);
            this.Principal = this.Context.User as UserPrincipal;
        }

        private void Page_Load(object sender, EventArgs e)
        {
            if (this.Principal.SysUser.IsAdmin == 0)
            {
                throw new ApplicationException(string.Format("User: {0} not has privilege to access this page.", this.Principal.SysUser.LoginName));
            }
            if (!this.Page.IsPostBack)
            {
                this.MessageRow.Visible = false;
                this.InitPage();
            }
        }

        private void ShowMessage(Color fcolor, string message)
        {
            this.MessageRow.Visible = true;
            this.MessageRow.Cells[0].InnerHtml = string.Format("<FONT COLOR='{0}' STYLE='FONT-SIZE:12px'>&nbsp;{1}</FONT>", fcolor.Name, message);
        }

        private void tvRoles_NodeCheckChanged(object sender, TreeViewNodeEventArgs e)
        {
            if (e.Node.Value.StartsWith("ROLE"))
            {
                foreach (TreeViewNode child in e.Node.Nodes)
                {
                    child.Checked = e.Node.Checked;
                }
            }
        }
    }
}

